package com.ruoyi.service.service.impl;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.validation.Validator;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanValidators;
import com.ruoyi.service.mapper.ServiceChargeItemMapper;
import com.ruoyi.service.domain.ServiceChargeItem;
import com.ruoyi.service.service.IServiceChargeItemService;

/**
 * 收费项目Service业务层处理
 * 
 * @author yepanpan
 * @date 2025-04-21
 */
@Service
public class ServiceChargeItemServiceImpl implements IServiceChargeItemService 
{
    private static final Logger log = LoggerFactory.getLogger(ServiceChargeItemServiceImpl.class);

    @Autowired
    private ServiceChargeItemMapper serviceChargeItemMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;

    @Autowired
    protected Validator validator;
    /**
     * 查询收费项目
     * 
     * @param id 收费项目主键
     * @return 收费项目
     */
    @Override
    public ServiceChargeItem selectServiceChargeItemById(Long id)
    {
        return serviceChargeItemMapper.selectServiceChargeItemById(id);
    }

    /**
     * 查询收费项目列表
     * 
     * @param serviceChargeItem 收费项目
     * @return 收费项目
     */
    @Override
    public List<ServiceChargeItem> selectServiceChargeItemList(ServiceChargeItem serviceChargeItem)
    {
        return serviceChargeItemMapper.selectServiceChargeItemList(serviceChargeItem);
    }

    /**
     * 新增收费项目
     * 
     * @param serviceChargeItem 收费项目
     * @return 结果
     */
    @Override
    public int insertServiceChargeItem(ServiceChargeItem serviceChargeItem)
    {
        ServiceChargeItem old = serviceChargeItemMapper.selectServiceChargeItemByCode(serviceChargeItem.getDeptId(), serviceChargeItem.getCode());
        if(old != null){
            throw new ServiceException("收费项目已存在，同一区域不同有相同的收费项目");
        }
        serviceChargeItem.setCreateTime(DateUtils.getNowDate());
        return serviceChargeItemMapper.insertServiceChargeItem(serviceChargeItem);
    }

    /**
     * 修改收费项目
     * 
     * @param serviceChargeItem 收费项目
     * @return 结果
     */
    @Override
    public int updateServiceChargeItem(ServiceChargeItem serviceChargeItem)
    {
        ServiceChargeItem old = serviceChargeItemMapper.selectServiceChargeItemByCode(serviceChargeItem.getDeptId(), serviceChargeItem.getCode());
        if(old != null && !old.getId().equals(serviceChargeItem.getId())){
            throw new ServiceException("收费项目已存在，同一区域不同有相同的收费项目");
        }
        serviceChargeItem.setUpdateTime(DateUtils.getNowDate());
        return serviceChargeItemMapper.updateServiceChargeItem(serviceChargeItem);
    }

    /**
     * 批量删除收费项目
     * 
     * @param ids 需要删除的收费项目主键
     * @return 结果
     */
    @Override
    public int deleteServiceChargeItemByIds(Long[] ids)
    {
        return serviceChargeItemMapper.deleteServiceChargeItemByIds(ids);
    }

    /**
     * 删除收费项目信息
     * 
     * @param id 收费项目主键
     * @return 结果
     */
    @Override
    public int deleteServiceChargeItemById(Long id)
    {
        return serviceChargeItemMapper.deleteServiceChargeItemById(id);
    }


    /**
   * 导入数据
   *
   * @param dataList 数据列表
   * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
   * @param operName 操作用户
   * @return 结果
   */
    @Override
    public String importData(List<ServiceChargeItem> dataList, Boolean isUpdateSupport, String operName){
        if (StringUtils.isNull(dataList) || dataList.size() == 0)
        {
            throw new ServiceException("导入数据不能为空！");
        }

        SysDept dc = new SysDept();
        dc.setDelFlag("0");
        dc.setDeptType("community");;
        List<SysDept> deptList = sysDeptMapper.selectDeptList(dc);
        if(deptList == null || deptList.isEmpty()){
            throw new ServiceException("请先添加区域信息");
        }

        Map<String, Long> deptMap = deptList.stream().collect(Collectors.toMap(SysDept::getDeptName, SysDept::getDeptId));

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (ServiceChargeItem row : dataList)
        {
            try
            {

                if(StringUtils.isEmpty(row.getDeptName())){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、收费项目 " + row.getName() + "、的区域信息不能为空");
                    continue;
                }
                Long deptId = deptMap.get(row.getDeptName().trim());
                if(deptId == null){
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、区域 " + row.getDeptName() + " 不存在");
                    continue;
                }
                row.setDeptId(deptId);

                BeanValidators.validateWithException(validator, row);
                // 验证是否存在旧数据
                ServiceChargeItem old = serviceChargeItemMapper.selectServiceChargeItemByCode(row.getDeptId(), row.getCode());
                if (StringUtils.isNull(old))
                {
                    row.setCreateBy(operName);
                    insertServiceChargeItem(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、收费项目 " + row.getName() + " 导入成功");
                }
                else if (isUpdateSupport)
                {
                    row.setId(old.getId());
                    row.setUpdateBy(operName);
                    updateServiceChargeItem(row);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、收费项目 " + row.getName() + " 更新成功");
                }
                else
                {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、收费项目 " + row.getName() + " 已存在");
                }
            }
            catch (Exception e)
            {
                failureNum++;
                String msg = "<br/>" + failureNum + "、收费项目 " + row.getName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0)
        {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        }
        else
        {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
